<?php

namespace App\Service;

use App\Constants\ErrorCode;
use App\Exception\CommonException;
use App\RedisAgent\SmsAgent;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use function Hyperf\Config\config;

class MailService {

    /**
     * 发送邮件
     * @param $email
     * @throws Exception
     */
    public function send($email): void {
        $mail = new PHPMailer();
        $mail->isSMTP();
        $mail->Host       = config('apiadmin.email.tx.host');       // SMTP 服务器地址
        $mail->SMTPAuth   = true;
        $mail->Username   = config('apiadmin.email.tx.username');   // SMTP 用户名
        $mail->Password   = config('apiadmin.email.tx.password');   // SMTP 密码
        $mail->SMTPSecure = config('apiadmin.email.tx.encrypt');    // 加密方式（可选）
        $mail->Port       = config('apiadmin.email.tx.port');       // SMTP 端口

        $mail->setFrom(config('apiadmin.email.tx.username'), 'SmartIp');
        $mail->addAddress($email);
        $mail->Subject = '欢迎使用SmartIp';
        $mail->isHTML();

        $code = (new SmsAgent())->getCode(md5($email));
        $bodyHtml   = file_get_contents(__DIR__ . '/tpl/MailCode.tpl');
        $mail->Body = str_replace('{{EMAIL_CODE}}', $code, $bodyHtml);

        if (!$mail->send()) {
            throw new CommonException("邮件发送失败：" . $mail->ErrorInfo, ErrorCode::NUMBER_MATCH_ERROR);
        }
    }
}
